let drawQrcode = require('../../utils/wxqrcode.js');
var app = getApp()
Page({
  data: {
    // 空调参数
    shake: 0,
    status: 0,
    temperature: 26,
    temperaturestr: '26',
    temperatureList: [16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],
    wind: 1,
    windstr: '低速',
    windList:['低速', '中速', '高速'],
    windDate:[1,2,3],
    workMode: 0,
    workTime: 0,
    workTimestr: '关',
    workTimeList: ['关','0.5小时', '1小时','1.5小时', '2小时','2.5小时', '3小时','3.5小时', '4小时','4.5小时', '5小时','5.5小时', '6小时','6.5小时', '7小时','7.5小时', '8小时','8.5小时', '9小时','9.5小时', '10小时','10.5小时', '11小时','11.5小时', '12小时','12.5小时', '13小时','13.5小时', '14小时','14.5小时', '15小时','15.5小时', '16小时','16.5小时', '17小时','17.5小时', '18小时','18.5小时', '19小时','19.5小时', '20小时','20.5小时', '21小时','21.5小时', '22小时','22.5小时', '23小时','23.5小时', '24小时'],
    workTimeDate: [0,30,60,90,120,150,180,210,240,270,300,330,360,390,420,450,480,510,540,570,600,630,660,690,720,750,780,810,840,870,900,930,960,990,1020,1050,1080,1110,1140,1170,1200,1230,1260,1290,1320,1350,1380,1410,1440],
    
    // ip
    motto: '',
    // 订单ID
    orderNo: null,
    outTradeNo: '',
    order: null,
    bookingDate: '',
    createTime: null,
    personNo: null,
    payTime:null,
    price: null,
    logistics: false,
    remark: '',
    campTypeInfo: {},
    tenttype: {},
    userInfo: '',
    checkNo: '',
    deviceNo: '',
    orderStatus: 0,   // 0未付款 1待商家确认 2待使用 3已完成 4已取消
    statusList: ['未付款', '已支付', '办理完', '完成']
  },  
  onLoad: function (options) {    
    console.log(options)
    this.setData({
      orderStatus: options.status,
      orderNo: options.orderno
    })
    var that = this;
    // 获取ip
    // this.getIp()
    wx.getUserInfo({
      success: function (res) {
        console.log(res)
        that.setData({
          userInfo: res.userInfo
        })  
      }
    })
    // 获取订单详情
    this.getOrderMsg(options.orderno)
  },
  // 获取ip
  // getIp () {
  //   var that = this
  //   wx.request({  // 获取ip
  //     url: 'http://ip-api.com/json',
  //     success: function (e) {
  //       that.setData({
  //         motto: e.data.query
  //       })
  //     },
  //     complete: function () {
  //       app.setLogCloud()
  //       wx.hideLoading()
  //     }
  //   })
  // },
  // 获取订单详情的接口
  getOrderMsg (orderNo) {
    console.log(orderNo)
    var that = this
    wx.showLoading({
      title: '订单详情获取中',
      mask: true
    })
    // 调用订单获取接口
    wx.request({
      url:  `${app.globalData.testApiUrl}/api/wx/order/getOrderDetail`,
      data: {
        orderId: orderNo
      },
      success: (res) => {
        console.log('接口调用成功', res)
        var outTradeNo = res.data.orderNo
        var createTime = res.data.createTime
        var payTime = res.data.payTime
        var price = res.data.price
        res.data.tenttype.tentTypeImg = res.data.tenttype.typePic ? app.globalData.testApiUrl + res.data.tenttype.typePic : ''
        that.setData({
          outTradeNo: outTradeNo,
          order: outTradeNo,
          createTime: createTime,
          payTime: payTime,
          price: price,
          bookingDate: res.data.bookingDate,
          personNo: res.data.personNo,
          remark: res.data.remark,
          checkNo: res.data.checkNo,
          deviceNo: res.data.deviceNo,
          campTypeInfo: res.data.camp,
          tenttype: res.data.tenttype
        })
        if (this.data.checkNo && res.data.status == 1) {
          let size = {}
          size.w = wx.getSystemInfoSync().windowWidth / 750 * 600
          size.h = size.w
          drawQrcode({
            width: size.w,
            height: size.h,
            canvasId: 'myQrcode',
            // ctx: wx.createCanvasContext('myQrcode'),
            text: res.data.checkNo
            // v1.0.0+版本支持在二维码上绘制图片
          })
        }
        if (res.data.deviceNo && res.data.status == 2) {
          // 获取空调状态
          this.getCondStatus()
        }
        wx.hideLoading()
      },
      fail: (error) => {
        consoel.log('接口调用失败', error)
        wx.hideLoading()
      },
      complete: function (e) {
        app.errorDate.backData = e.data
        app.errorDate.statusCode = e.statusCode
        app.errorDate.route = 'orderDetail'
        app.errorDate.interface = '/api/wx/order/getOrderDetail'
        app.setLogCloud()
        wx.hideLoading()
      }
    })
  },
  // 取消订单
  cancelOrder: function () {
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定要取消订单吗？',
      success (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '取消订单中',
            mask: true
          })
          wx.request({
            url:  `${app.globalData.testApiUrl}/api/wx/order/deleteOrder`,
            data: {
              orderId: that.data.orderNo
            },
            success: (res) => {
              wx.hideLoading()
              wx.showToast({
                title: '取消成功',
                duration: 2000
              })
              setTimeout(() => {
                wx.redirectTo({
                  url: '/pages/index/index',
                })
              }, 2000)
            },
            fail: (error) => {
              console.log('接口调用失败', error)
            },
            complete: function (e) {
              app.errorDate.backData = e.data
              app.errorDate.statusCode = e.statusCode
              app.errorDate.route = 'index'
              app.errorDate.interface = '/api/wx/order/deleteOrder'
              app.setLogCloud()
              wx.hideLoading()
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  calling: function () {
    wx.makePhoneCall({
      phoneNumber: '18316588252',
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })
  },
  // 提交订单
  apply: function () {
    var that = this
    var params = {
      appid: app.globalData.appId,
      openid: app.globalData.openId,
      nonceStr: app.randomWord(),
      notifyUrl: `${app.globalData.testApiUrl}/api/wx/pay/notify/order`,
      body: this.data.remark,
      totalFee: this.data.price * 100,
      tradeType: 'JSAPI',
      outTradeNo: this.data.outTradeNo,
      spbillCreateIp: '218.16.63.137'
    }
    console.log(params)
    wx.request({
      url: `${app.globalData.testApiUrl}/api/wx/pay/createOrder`,
      method: 'POST',
      // data: {
      //   appid: app.globalData.appId,
      //   openid: app.globalData.openId,
      //   nonceStr: app.randomWord(),
      //   notifyUrl: `${app.globalData.testApiUrl}/api/wx/pay/notify/order`,
      //   body: this.data.remark,
      //   // totalFee: res.data.price, // 分
      //   totalFee: this.data.price,
      //   tradeType: 'JSAPI',
      //   outTradeNo: this.data.outTradeNo,
      //   spbillCreateIp: '218.16.63.137'
      //   // spbillCreateIp: app.globalData.ip
      // },
      data: params,
      success: (res) => {
        wx.requestPayment({
          provider: 'wxpay',
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.packageValue,
          signType: res.data.signType,
          paySign: res.data.paySign,
          appId: app.globalData.openId,
          success: res => {
            console.log(res)
            wx.showToast({
              title: '支付成功',
              duration: 2000
            })
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/index/index',
              })
            }, 2000)
          },
          fail: (error) => {
            // wx.redirectTo({
            //   url: '/pages/index/index',
            // })
          },
          complete: function (e) {
            app.errorDate.backData = e.data
            app.errorDate.statusCode = e.statusCode
            app.errorDate.route = 'orderDetail'
            app.errorDate.interface = '/api/wx/pay/notify/order'
            app.setLogCloud()
            wx.hideLoading()
          }
        })
      },
      fail: (error) => {

      },
      complete: function (e) {
        // console.log(params)
        app.errorDate.params = params
        app.errorDate.backData = e.data
        app.errorDate.statusCode = e.statusCode
        app.errorDate.route = 'orderDetail'
        app.errorDate.interface = '/api/wx/pay/createOrder'
        app.setLogCloud()
        wx.hideLoading()
      }
    })
  },
  // 
  toApply: function() {
    // wx.navigateTo({
    //   url: '../applyRefund/applyRefund',
    // })
  },
  // 跳到评论
  toEvaluate: function() {
    wx.navigateTo({
      url: '../evaluate/evaluate',
    })
  },
   // 设定空调温度
   pickerTemperature: function(el) {
    var that = this
    var item = parseInt(el.detail.value)
    this.setData({
      temperature: that.data.temperatureList[item],
      temperaturestr: that.data.temperatureList[item]
    })
  },
  // 设定风速
  pickerWindList: function(el) {
    var that = this
    var item = parseInt(el.detail.value)
    this.setData({
      wind: that.data.windDate[item],
      windstr: that.data.windList[item]
    })
  },
  // 设定定时
  pickerWorkTimeList: function(el) {
    var that = this
    var item = parseInt(el.detail.value)
    this.setData({
      workTime: that.data.workTimeDate[item],
      workTimestr: that.data.workTimeList[item]
    })
  },
  // 空调控制按钮
  ktkz: function() {
    var that = this
    var thatstatus = that.data.status
    if (thatstatus) {
      thatstatus = 1
    } else {
      thatstatus = 0
    }
    var thatshake = that.data.shake
    if (thatshake) {
      thatshake = 1
    } else {
      thatshake = 0
    }
    var thatworkMode = that.data.workMode
    if (thatworkMode) {
      thatworkMode = 1
    } else {
      thatworkMode = 0
    }
    // 调用接口
    wx.request({
      url: `${app.globalData.testApiUrl}/api/wx/icebox/controlDevice`,
      method: 'post',
      data: {
        devEui: that.data.deviceNo,
        shake: thatshake,
        status: thatstatus,
        temperature: that.data.temperature,
        userId: app.globalData.userId,
        wind: that.data.wind,
        workMode: thatworkMode,
        workTime: that.data.workTime,
      }
    })
  },
  // 获取当前空调的状态
  getCondStatus: function() {
    var that = this
    // 调用状态查询接口
    wx.request({
      url: `${app.globalData.testApiUrl}/api/wx/icebox/showStatus`,
      data: {
        devEui: that.data.deviceNo,
        userId: app.globalData.userId
      },
      success: (res) => {
        console.log('空调状态获取成功', res)
        // 这里需要把获取到的相关信息赋给本地相对应的变量
        // 获取空调状态
        var thatstatus = res.data.status
        if (thatstatus === 1) {
          thatstatus = true
        } else {
          thatstatus = false
        }
        var thatshake = res.data.shake
        if (thatshake === 1) {
          thatshake = true
        } else {
          thatshake = false
        }
        var thatworkMode = res.data.workMode
        if (thatworkMode === 1) {
          thatworkMode = true
        } else {
          thatworkMode = false
        }
        var thatwind = res.data.wind
        // 获取数据在数组中的角标
        var thatwindIndex = that.getArrayIndex(thatwind, that.data.windDate)
        var thatwindstr = '低速'
        if (thatwindIndex > 0) {
          thatwindstr = that.data.windList[thatwindIndex]
        }
        var workTime = res.data.workTime
        var workTimeIndex = that.getArrayIndex(workTime, that.data.workTimeDate)
        var workTimestr = '关'
        if (workTimeIndex > 0) {
          workTimestr = that.data.workTimeList[workTimeIndex]
        }
        var temprature = res.data.temperature
        var tempratureIndex = that.getArrayIndex(temprature, that.data.temperatureList)
        var tempraturestr = '26'
        if (tempratureIndex > 0) {
          tempraturestr = that.data.tempratureList[tempratureIndex]
        }
        // 设置参数到本地变量
        that.setData({
          status: thatstatus,
          shake: thatshake,
          workMode: thatworkMode,
          wind: thatwind,
          windstr: thatwindstr,
          workTime: workTime,
          workTimestr: workTimestr,
          temprature: temprature,
          tempraturestr: tempraturestr,
        })
      },
      fail: (error) => {
        console.log('空调状态获取成功', error)
      },
      complete: function (e) {
        app.errorDate.backData = e.data
        app.errorDate.statusCode = e.statusCode
        app.errorDate.route = 'orderDetail'
        app.errorDate.interface = '/api/wx/icebox/showStatus'
        app.setLogCloud()
        wx.hideLoading()
      }
    })
  },
  // 根据值获取，某个数据在数组中的位置
  getArrayIndex (num, dataList) {
    var index = 0
    for (var i in dataList) {
      if (num === dataList[i]) {
        return index
      }
      index ++
    }
    return -1
  }
})
